<template>
	<view class="container">
		<view class="header">
			<text class="title">工单详情</text>
		</view>
		<view class="section-card">
			<view class="info-grid">
				<view class="info-cell">
					<text class="cell-label">工单编号：</text>
					<text class="cell-value">{{ task.id }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">工单类型：</text>
					<text class="cell-value">{{ task.title }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">工单状态：</text>
					<text class="cell-value status-tag"
						:class="getStatusClass(selectedOperateStatus)">{{ formatOperateStatus(selectedOperateStatus) }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">申请时间：</text>
					<text class="cell-value">{{ task.createTime }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">提交人：</text>
					<text class="cell-value">{{ task.userName }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">提交人角色：</text>
					<text class="cell-value">{{ task.name }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">紧急程度：</text>
					<text class="cell-value">{{ formatUrgency(task.urgency) }}</text>
				</view>
				<view class="info-cell">
					<text class="cell-label">超时预警：</text>
					<text class="cell-value"
						:class="task.TimeOutOperate ? 'timeout-yes' : 'timeout-no'">{{ formatTimeOut(task.TimeOutOperate) }}</text>
				</view>
			</view>
		</view>

		<view class="action-buttons">
			<button v-if="canClaim()" @click="claimOrder">接单</button>
			<button v-if="canDelegate()" @click="delegateOrder">委派协作</button>
			<button v-if="canAcceptDelegate()" @click="acceptDelegate">接受委派协作</button>
			<button v-if="canFinishDelegate()" @click="finishDelegate">完成委派协作</button>
			<button v-if="canCompleteOrder()" @click="completeOrder">完成工单操作</button>
			<button v-if="canViewCompletionForm()" @click="viewCompletionForm">查看回单</button>
		</view>
		<view v-if="delegateModalVisible" class="approve-modal">
			<view class="modal-box">
				<view class="modal-header">
					<text class="modal-title">委派协作</text>
					<view class="modal-close" @click="closedelegate">关闭</view>
				</view>
				<view class="filter-item">
					<label>委派职位</label>
					<text>{{ selectedTypeText }}</text>
				</view>

				<view class="modal-body">
					<view class="role-list">
						<view v-for="role in typeOptions" :key="role.id" @click="selectRole(role)"
							:class="['role-item', { 'selected': role.id === delegateData.roleId }]">
							<text>{{ role.name }}</text>
						</view>
					</view>
				</view>
				<view class="filter-item">
					<label>委派原因</label>
					<input v-model="delegateData.comment" placeholder="请输入委派原因" />
				</view>
				<view class="modal-footer">
					<button @click="submitdelegateTask" class="blue-button">提交</button>
					<button @click="closedelegate" class="blue-button">取消</button>
				</view>
			</view>
		</view>
		<view v-if="completionModalVisible" class="approve-modal">
			<view class="modal-box">
				<view class="modal-header">
					<text class="modal-title">填写回单</text>
					<!-- <view class="modal-close" @click="closeCompletionModal">关闭</view> -->
				</view>
				<view class="modal-body">
					<view class="filter-item">
						<label>故障原因：</label>
						<input v-model="completionData.reason" placeholder="请输入故障原因" />
					</view>
					<view class="filter-item">
						<label>解决措施：</label>
						<input v-model="completionData.solution" placeholder="请输入解决措施" />
					</view>
					<view class="filter-item">
						<label>维修结果：</label>
						<input v-model="completionData.result" placeholder="请输入维修结果" />
					</view>
				</view>
				<view class="modal-footer">
					<button @click="submitCompletion" class="blue-button">提交</button>
					<!-- 					<button @click="closeCompletionModal" class="blue-button">取消</button> -->
				</view>
			</view>
		</view>
		<!-- 其他内容 -->
		<view v-if="checkmodalvisiable" class="approve-modal">
			<view class="modal-box">
				<view class="modal-header">
					<text class="modal-title">回单详情</text>
					<view class="modal-close" @click="closecheck">关闭</view>
				</view>
				<view class="modal-body">
					<view class="filter-item">
						<label>工单ID：</label>
						<text>{{ task.orderId }}</text>
					</view>
					<view class="filter-item">
						<label>操作员姓名：</label>
						<text>{{ task.operatorName }}</text>
					</view>
					<view class="filter-item">
						<label>操作员职位：</label>
						<text>{{ task.operatorRoleName }}</text>
					</view>
					<view class="filter-item">
						<label>完成时间：</label>
						<text>{{task.completionTime}}</text>
					</view>
					<view class="filter-item">
						<label>故障原因：</label>
						<text>{{task.reason}}</text>
					</view>
					<view class="filter-item">
						<label>故障解决措施：</label>
						<text>{{task.solution}}</text>
					</view>
					<view class="filter-item">
						<label>执行结果</label>
						<text>{{task.result}}</text>
					</view>
					<view class="filter-item">
						<label></label>
						<text></text>
					</view>
					<view class="filter-item">
						<label></label>
						<text></text>
					</view>
				</view>
				<view class="modal-footer">
					<button @click="closecheck" class="blue-button">关闭</button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				task: {}, // 当前工单详情
				selectedOrderId: null, // 选中的工单ID
				selectedOperateStatus: null, // 选中的工单状态
				delegateModalVisible: false,
				completionModalVisible: false, // 填写回单模态窗口的可见性
				checkmodalvisiable: false,
				delegateData: {
					orderId: 0,
					comment: '',
					roleId: ''
				},
				completionData: {
					orderId: 0,
					reason: '',
					solution: '',
					result: ''
				},
				typeOptions: [],
				selectedTypeText: ""
			};
		},
		onLoad(options) {
			this.selectedOrderId = options.orderId;
			this.delegateData.orderId = options.orderId;
			this.completionData.orderId = options.orderId;
			this.selectedOperateStatus = parseInt(options.operateStatus, 10);
			this.loadTaskDetails();
			this.fetchTypeList();
		},
		methods: {
			async loadTaskDetails() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8082/api/common/orderDetail/${this.selectedOrderId}`,
						method: 'get',
						header: {
							'Authorization': 'Bearer ' + token
						}
					});

					if (res.statusCode === 200 && res.data.code === 1) {
						this.task = res.data.data;
					} else {
						uni.showToast({
							title: "加载工单详情失败",
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},
			formatUrgency(urgency) {
				switch (urgency) {
					case 1:
						return '低';
					case 2:
						return '中';
					case 3:
						return '高';
					default:
						return '未知';
				}
			},
			getStatusClass(operateStatus) {
				switch (operateStatus) {
					case 1:
						return 'status-wait';
					case 2:
						return 'status-processing';
					case 3:
						return 'status-assigning';
					case 4:
						return 'status-delegating';
					case 5:
						return 'status-finished';
					case 6:
						return 'status-completed';
					default:
						return '';
				}
			},

			formatTimeOut(timeOut) {
				return timeOut ? '是' : '否';
			},
			formatOperateStatus(operateStatus) {
				switch (operateStatus) {
					case 1:
						return "待接单";
					case 2:
						return "操作中";
					case 3:
						return "待接受委派";
					case 4:
						return "委派中";
					case 5:
						return "完成委派";
					case 6:
						return "已完成";
					default:
						return '未知';
				}
			},
			claimOrder() {
				this.submitClaimOrder();
			},
			// 提交接单请求
			async submitClaimOrder() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8082/api/operate/claim/${this.selectedOrderId}`,
						method: 'PUT',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 1) {
								uni.showToast({
									title: "接单成功",
									icon: 'success'
								});
								uni.redirectTo({
									url: '/pages/tabbar/ticket/ticket'
								});
							} else {
								uni.showToast({
									title: res.data.msg || '接单失败',
									icon: 'fail'
								});
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "请求接口失败" + err.message,
								icon: 'loading'
							});
						}
					});
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},
			delegateOrder() {
				this.delegateModalVisible = true;
			},
			// 接受委派操作
			acceptDelegate() {
				this.submitAcceptDelegate();
			},

			// 提交接受委派请求
			async submitAcceptDelegate() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8082/api/operate/delegate/claim/${this.selectedOrderId}`,
						method: 'PUT',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 1) {
								uni.showToast({
									title: "接受委派成功",
									icon: 'success'
								});
								uni.redirectTo({
									url: '/pages/tabbar/ticket/ticket'
								});
							} else {
								uni.showToast({
									title: res.data.msg || '接受委派失败',
									icon: 'fail'
								});
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "请求接口失败" + err.message,
								icon: 'none'
							});
						}
					});
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},

			// 完成委派操作
			finishDelegate() {
				this.submitFinishDelegate();
			},

			// 提交完成委派请求
			async submitFinishDelegate() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8082/api/operate/delegate/finish/${this.selectedOrderId}`,
						method: 'PUT',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 1) {
								uni.showToast({
									title: "完成委派成功",
									icon: 'success'
								});
								uni.redirectTo({
									url: '/pages/tabbar/ticket/ticket'
								});
							} else {
								uni.showToast({
									title: res.data.msg || '完成委派失败',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "请求接口失败" + err.message,
								icon: 'none'
							});
						}
					});
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},

			completeOrder() {
				this.submitCompleteOrder();

			},
			viewCompletionForm() {
				this.viewCompletion();
			},
			async viewCompletion() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8082/api/common/completionForm/${this.selectedOrderId}`,
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					});

					if (res.statusCode === 200 && res.data.code === 1) {
						this.task = res.data.data; // 假设返回的数据结构与示例中的data结构一致
						uni.showToast({
							title: "查看回单成功",
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.data.msg || '查看回单失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},
			canClaim() {
				return this.selectedOperateStatus === 1;
			},
			canDelegate() {
				return this.selectedOperateStatus === 2;
			},
			canAcceptDelegate() {
				return this.selectedOperateStatus === 3;
			},
			canFinishDelegate() {
				return this.selectedOperateStatus === 4;
			},
			canCompleteOrder() {
				return this.selectedOperateStatus === 2;
			},
			canViewCompletionForm() {
				return this.selectedOperateStatus === 6;
			},
			async fetchTypeList() {
				try {
					this.token = uni.getStorageSync('token');
					const res = await uni.request({
						url: "http://localhost:8082/user/roleList", // 获取类型列表的接口地址
						header: {
							'Authorization': 'Bearer ' + this.token, // 使用 Token
							'Content-Type': 'application/json'
						},
						method: 'GET'
					});

					if (res.statusCode === 200 && res.data.code === 1) {
						this.typeOptions = res.data.data.map(item => item);
					} else {
						uni.showToast({
							title: '加载职位列表失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求接口失败',
						icon: 'none'
					});
				}
			},
			closedelegate() {
				this.delegateModalVisible = false;
			},
			closeCompletionModal() {
				this.completionModalVisible = false;
			},

			closecheck() {
				this.checkmodalvisiable = false;
			},
			selectRole(role) {
				this.selectedTypeText = role.name;
				this.delegateData.roleId = role.id;
			},
			async submitdelegateTask() {
				if (!this.delegateData.comment) {
					uni.showToast({
						title: '委派原因不能为空',
						icon: 'none'
					});
					return;
				}
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: "http://localhost:8082/api/operate/delegate",
						method: 'POST',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						data: {
							orderId: this.delegateData.orderId,
							reason: this.delegateData.comment,
							roleId: this.delegateData.roleId
						}
					});

					if (res.statusCode === 200 && res.data.code === 1) {
						uni.showToast({
							title: "委派成功",
							icon: 'success'
						});
						this.closedelegate();
					} else {
						uni.showToast({
							title: res.data.msg || '委派失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求接口失败' + err.message,
						icon: 'none'
					});
				}
			},

			submitCompletion() {
				if (!this.completionData.reason || !this.completionData.solution || !this.completionData.result) {
					uni.showToast({
						title: '所有字段均为必填',
						icon: 'none'
					});
					return;
				}
				try {
					const token = uni.getStorageSync('token');
					const res = uni.request({
						url: "http://localhost:8082/api/operate/completion_form",
						method: 'POST',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						data: {
							orderId: this.completionData.orderId,
							reason: this.completionData.reason,
							solution: this.completionData.solution,
							result: this.completionData.result
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 1) {
								uni.showToast({
									title: "填写回单成功",
									icon: 'success'
								});
								this.closeCompletionModal();
							} else {
								this.closeCompletionModal();
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "请求接口失败" + err.message,
								icon: 'none'
							});
						}
					});
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			},
			submitCompleteOrder() {
				try {

					const token = uni.getStorageSync('token');
					const res = uni.request({
						url: `http://localhost:8082/api/operate/complete/${this.selectedOrderId}`,
						method: 'PUT',
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json'
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.code === 1) {
								uni.showToast({
									title: "工单完成成功",
									icon: 'success'
								});
								this.completionModalVisible = true;
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "请求接口失败" + err.message,
								icon: 'none'
							});
						}
					});
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 16px;
		background-color: #f5f7fa;
	}

	.order-detail {
		padding: 20rpx;
		background: #f4f8fb;
		min-height: 100vh;
	}

	.header {
		background: linear-gradient(to right, #3b82f6, #2563eb);
		color: white;
		padding: 20rpx;
		text-align: center;
		border-radius: 12rpx;
		margin-bottom: 24rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}


	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		margin-bottom: 20rpx;
		color: #2c3e50;
	}

	.section-card {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.info-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx 4%;
	}

	.info-cell {
		width: 48%;
		margin-bottom: 20rpx;
	}

	.cell-label {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 6rpx;
	}

	.cell-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.status-tag {
		padding: 4rpx 12rpx;
		border-radius: 8rpx;
		color: #fff;
		font-size: 24rpx;
	}

	.status-wait {
		background: #f39c12;
	}

	.status-processing {
		background: #3498db;
	}

	.status-assigning {
		background: #59aee7;
	}

	.status-delegating {
		background: #2980b9;
	}

	.status-completed {
		background: #2ecc71;
	}

	.status-finished {
		background: #95a5a6;
	}

	.timeout-yes {
		color: #e74c3c;
	}

	.timeout-no {
		color: #2ecc71;
	}

	.action-buttons {
		display: flex;
		gap: 12px;
		flex-wrap: wrap;
		margin-top: 20px;
	}

	button {
		flex: 1;
		background: #2b6cb0;
		color: #fff;
		border: none;
		border-radius: 8px;
		padding: 12px 0;
		font-weight: bold;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	button.secondary {
		background: #e5e7eb;
		color: #374151;
	}

	.approve-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		/* 半透明背景 */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-box {
		background: #ffffff;
		padding: 24px;
		border-radius: 12px;
		width: 80%;
		max-width: 360px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}

	.modal-title {
		font-size: 18px;
		color: #2b6cb0;
	}

	.modal-close {
		color: #9ca3af;
		cursor: pointer;
	}

	.filter-item {
		margin-bottom: 16px;
	}

	.filter-item label {
		display: block;
		color: #6b7280;
		margin-bottom: 8px;
	}

	.filter-item input {
		width: 100%;
		padding: 10px;
		border: 1px solid #d1d5db;
		border-radius: 8px;
	}

	.role-list {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
	}

	.role-item {
		padding: 8px 12px;
		background: #f3f4f6;
		border-radius: 8px;
		cursor: pointer;
	}

	.role-item.selected {
		background: #2b6cb0;
		color: #ffffff;
	}

	.modal-footer {
		display: flex;
		gap: 12px;
		justify-content: flex-end;
	}

	.blue-button {
		background: #2b6cb0;
		color: #ffffff;
		border-radius: 8px;
		padding: 10px 20px;
	}
</style>